<?php
namespace App\WebSocket\Controller;

use App\Storage\Emoji;
use App\Task\BroadcastTask;
use App\WebSocket\Actions\Broadcast\BroadcastMessage;
use EasySwoole\EasySwoole\Swoole\Task\TaskManager;
use EasySwoole\Socket\AbstractInterface\Controller;
use EasySwoole\Socket\Client\WebSocket;

class Broadcast extends Controller {

    /**
     * 广播消息给群聊中的所有人
     */
    function roomBroadcast() {

        /** @var WebSocket $client */
        $client = $this->caller()->getClient();
        $broadcastPayload = $this->caller()->getArgs();
        if (!empty($broadcastPayload) && isset($broadcastPayload['content'])) {
            $allEmoji = Emoji::getInstance()->getEmoji();
            foreach($allEmoji as $_k => $_v){
                $broadcastPayload['content'] = str_replace($_k,$_v,$broadcastPayload['content']);
            }
            $message = new BroadcastMessage();
            $message->setFromUserFd($client->getFd());
            $message->setContent($broadcastPayload['content']);
            $message->setType($broadcastPayload['type']);
            $message->setSendTime(date('Y-m-d H:i:s'));
            TaskManager::async(new BroadcastTask(['payload' => $message->__toString(), 'fromFd' => $client->getFd(), 'shopId' => $broadcastPayload['shopId']]));
        }
        $this->response()->setStatus($this->response()::STATUS_OK);
    }

}